package com.campus.service.impl;

import com.campus.pojo.vo.CaptchaVO;
import com.campus.service.CaptchaService;
import com.campus.utils.CaptchaUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {

    private final RedisTemplate redisTemplate;

    @Override
    public CaptchaVO getCaptcha() throws IOException {
        // 生成图形验证码
        CaptchaUtil.CaptchaInfo captchaInfo = CaptchaUtil.generateCaptcha();
        // 生成唯一标识
        String key = UUID.randomUUID().toString();

        // 存入redis 图形验证码60秒后过期
        redisTemplate.opsForValue().set(key, captchaInfo.getCode(), 60, TimeUnit.SECONDS);

        return CaptchaVO.builder()
                .key(key)
                .captchaImage(captchaInfo.getBase64Image())
                .build();
    }
}
